package service

import (
	"context"
	com_model "elflog/common/com-model"
	"elflog/common/errs"
	"elflog/common/utils/id_util"
	"elflog/module/module-account/model"
	"errors"
	"github.com/bluele/gcache"
	"github.com/jinzhu/gorm"
	"time"
)

func (a *ModuleAccountService) CreateLogger(ctx context.Context, logger *model.CreateAccountLoggerModel) error {
	return a.dao.Dao.GetDb(ctx).Create(&model.AccountLogger{
		Model: com_model.Model{
			Id:        id_util.GetUuid(),
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			DeletedAt: nil,
		},
		AccountId:         logger.AccountId,
		Name:              logger.Name,
		MaxSaveCount:      logger.MaxSaveCount,
		MaxSaveDuration:   logger.MaxSaveDuration,
		FieldNameStrategy: logger.FieldNameStrategy,
		Key:               logger.Key,
		Secret:            logger.Secret,
	}).Error
}

// 缓存
func (a *ModuleAccountService) GetLoggerByKey(ctx context.Context, key string) (*model.AccountLogger, error) {
	cachedLogger, err := a.loggerCache.Get(key)
	if err == nil {
		return cachedLogger.(*model.AccountLogger), nil
	}
	if !errors.Is(err, gcache.KeyNotFoundError) {
		return nil, errs.NewInternal().WithError(err)
	}

	logger := new(model.AccountLogger)
	err = a.dao.Dao.GetDb(ctx).Model(logger).Find(logger, "`key`=?", key).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			return nil, nil
		}
		return nil, err
	}

	err = a.loggerCache.Set(key, logger)
	if err != nil {
		return nil, errs.NewInternal().WithError(err)
	}

	return logger, nil
}

func (a *ModuleAccountService) GetAllLoggerSelective(ctx context.Context) ([]*model.AccountLogger, error) {
	var columns = "id,account_id,name,max_save_count,max_save_duration,field_name_strategy"
	var accounts []*model.AccountLogger
	err := a.dao.Dao.GetDb(ctx).Select(columns).Find(&accounts).Error
	if err != nil {
		return nil, errs.NewInternal().WithError(err)
	}
	return accounts, nil
}
